<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button type="primary" :icon="Upload" plain @click="batchAdd">导入数据</el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <DataElementDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="DataElement">
import { ref, reactive, computed, onMounted } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import DataElementDrawer from "./dataElementDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Download, Upload } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { useDownload } from "@/hooks/useDownload";
import { ElMessageBox } from "element-plus";
import { useDateFormat } from "@vueuse/core";
import { ExportColType } from "@/enums/sysEnum";
import { Model } from "../modeTypes";
import { useDataStore } from "@/stores/modules/data";
import { dateRender, enumRender, enName2CnNameRender, userRender } from "@/hooks/useColumnRender";

// ProTable 实例
const proTable = ref<ProTableInstance>();
const dataStore = useDataStore();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

const isOrNotList = computed(() => dataStore.getEnumByCsName("IS_NOT"));
const userList = computed(() => dataStore.userList);
const abstractElements = computed(() => dataStore.abstractElements);

onMounted(() => {
  dataStore.findEnumByCsName("IS_NOT");
  dataStore.findUserList();
  dataStore.findAbstractElements();
});

const initVar = reactive({
  tbName: "dataElement"
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  return apiService.findPage(initVar.tbName, params.condition, params.options);
};

// 表格配置项
const columns = reactive<ColumnProps<Model.DataElement>[]>([
  { type: "index", label: "序号", width: 65 },
  { prop: "cnName", label: "中文名称", search: { el: "input", like: true }, width: 180 },
  { prop: "enName", label: "英文名称", search: { el: "input", like: true }, width: 160 },
  {
    prop: "abstractElementCnName",
    label: "抽象元素",
    width: 120,
    render: scope => enName2CnNameRender(scope, abstractElements),
    fieldNames: { value: "cnName", label: "enName" }
  },
  {
    prop: "type",
    label: "类型",
    search: { el: "select", props: { filterable: true } },
    width: 100,
    enum: () => apiService.findClassify("DataElementType"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "description", label: "描述", search: { el: "input", like: true }, width: 300 },
  { prop: "ownerUser", label: "负责人", search: { el: "input", like: true }, width: 100 },
  { prop: "viewName", label: "界面显示名称", search: { el: "input", like: true }, width: 120 },
  {
    prop: "isBase",
    label: "是否基准元素",
    width: 120,
    enum: isOrNotList,
    search: { el: "select", props: { filterable: true } },
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "baseDataElementCnName", label: "对应基准元素", width: 120 },
  {
    prop: "isEncrypt",
    label: "是否加密",
    width: 90,
    enum: isOrNotList,
    search: { el: "select", props: { filterable: true } },
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "isMasking",
    label: "是否脱敏",
    width: 90,
    enum: isOrNotList,
    search: { el: "select", props: { filterable: true } },
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "businessDomain", label: "业务领域", search: { el: "input", like: true }, width: 100 },
  { prop: "create_user", label: "创建人", width: 100, render: scope => userRender(scope, userList) },
  { prop: "create_at", label: "创建时间", width: 120, render: dateRender },
  { prop: "operation", label: "操作", fixed: "right", width: 220 }
]);

const getExcelConfig = (): any => {
  return {
    params: proTable.value?.searchParam,
    tableName: initVar.tbName,
    // keyPropName: "enName",
    enumTypes: ["IS_NOT", "DataElementType"],
    tableConfigs: [
      { tableName: "users", fields: ["_id", "userName"] },
      { tableName: "abstractElement", fields: ["enName", "cnName"] }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "中文名称", width: 15, ext: { prop: "cnName", type: ExportColType.DEFAULT } },
      { header: "英文名称", width: 15, ext: { prop: "enName", type: ExportColType.DEFAULT } },
      {
        header: "抽象元素",
        width: 15,
        ext: {
          prop: "abstractElementCnName",
          type: ExportColType.TABLE,
          key: "abstractElement",
          label: "cnName",
          value: "enName"
        }
      },
      {
        header: "类型",
        width: 10,
        ext: { prop: "type", type: ExportColType.ENUM, key: "DataElementType", label: "name", value: "value" }
      },
      { header: "描述", width: 20, ext: { prop: "description", type: ExportColType.DEFAULT } },
      { header: "负责人", width: 10, ext: { prop: "ownerUser", type: ExportColType.DEFAULT } },
      { header: "界面显示名称", width: 12, ext: { prop: "viewName", type: ExportColType.DEFAULT } },
      {
        header: "是否基础元素",
        width: 12,
        ext: { prop: "isBase", type: ExportColType.ENUM, key: "IS_NOT", label: "name", value: "value" }
      },
      { header: "对应基准元素", width: 15, ext: { prop: "baseDataElementCnName", type: ExportColType.DEFAULT } },
      {
        header: "是否加密",
        width: 12,
        ext: { prop: "isEncrypt", type: ExportColType.ENUM, key: "IS_NOT", label: "name", value: "value" }
      },
      {
        header: "是否脱敏",
        width: 8,
        ext: { prop: "isMasking", type: ExportColType.ENUM, key: "IS_NOT", label: "name", value: "value" }
      },
      { header: "业务领域", width: 10, ext: { prop: "businessDomain", type: ExportColType.DEFAULT } },
      {
        header: "创建人",
        width: 10,
        ext: { prop: "create_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "创建时间", width: 15, ext: { prop: "create_at", type: ExportColType.DATE } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(
      apiService.commonExport,
      `数据元素清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`,
      "",
      getExcelConfig(),
      false
    )
  );
};

// 导入数据
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "数据元素",
    defaultTip: "英文名称相同则跳过",
    coverTip: "英文名称相同则覆盖",
    isCover: true,
    tempUrl: "/template/dataElement",
    getTableList: proTable.value?.getTableList,
    importApi: apiService.commonImport,
    config: getExcelConfig()
  };
  dialogRef.value?.acceptParams(params);
};

// 删除数据元素
const deleteAccount = async (row: Model.DataElement) => {
  useHandleData(apiService.deleteById, initVar.tbName, row._id, "删除").then(() => proTable.value?.getTableList());
};

// 打开抽屉
const drawerRef = ref<InstanceType<typeof DataElementDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Model.DataElement> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? apiService.save : apiService.updateById,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
